package com.SmartHelmet.Web.APP;

import com.SmartHelmet.ViewModel.ResponseResult;
import com.SmartHelmet.config.returnCode;
import com.SmartHelmet.model.Email;
import com.SmartHelmet.model.master;
import com.SmartHelmet.model.token;
import com.SmartHelmet.service.MailService;
import com.SmartHelmet.service.TokenService;
import com.SmartHelmet.service.UserService;
import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Random;
import com.SmartHelmet.utils.RandomUtil;
import com.SmartHelmet.utils.CryptoUtil;

/**
 * Created by Administrator on 2016/12/5.
 */
@Controller
@RequestMapping("/app/api")
public class MailController {
    @Resource
    private MailService mailService;

    @Resource
    private UserService userService;

    @Resource
    private TokenService tokenService;

    @ResponseBody
    @RequestMapping(value="/sendmail", method=RequestMethod.POST,produces="text/html;charset=UTF-8")
    public String postSendMail(final Model model, final HttpServletRequest request,final HttpServletResponse response,HttpSession httpSession) {
        boolean sendResult = true;
        ResponseResult pr = new ResponseResult();

        if(request.getParameter("email")==null)
        {
            pr.setMessage("缺少必要的参数");
            pr.setCode(String.valueOf(returnCode.ERROR.ordinal()));
            return JSON.toJSONString(pr);
        }

        String emailStr=request.getParameter("email");
        master user=userService.getMasterByEmail(emailStr);
        if(user==null)
        {
            pr.setMessage("没有找到该用户");
            pr.setCode(String.valueOf(returnCode.NOT_FOUND.ordinal()));
            return JSON.toJSONString(pr);
        }

        //
        Email email = new Email();
        email.setToAddress(request.getParameter("email"));
        email.setFromAddress("no_reply@babaali.cc");
        email.setSubject("智能头盔找回密码");

        String vaildCode=RandomUtil.getFourRandom().toString();
        httpSession.setAttribute("vaildCode",vaildCode);
        //
        email.setContent("您的找回密码验证码为："+vaildCode);
        try {
            mailService.sendMail(email);
        } catch (Exception e) {
            e.printStackTrace();
            sendResult = false;
        }

        if (sendResult) {
            String tokenStr=tokenService.addToken(vaildCode);
            pr.setCode(String.valueOf(returnCode.SUCCESS.ordinal()));
            pr.setMessage("邮件发送成功");
            pr.setData(tokenStr);
            //
            return JSON.toJSONString(pr);
        } else {
            pr.setCode(String.valueOf(returnCode.ERROR.ordinal()));
            pr.setMessage("邮件发送失败");
            return JSON.toJSONString(pr);
        }
    }

    /**
     * 验证并设置新密码
     * @param model
     * @param request
     * @param response
     * @param httpSession
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/verifyEmailCode", method=RequestMethod.POST,produces="text/html;charset=UTF-8")
    public String verifyEmailCode(final Model model, final HttpServletRequest request,final HttpServletResponse response,HttpSession httpSession) {
        ResponseResult pr=new ResponseResult();
        if(request.getParameter("email")==null || request.getParameter("verifyCode")==null || request.getHeader("token")==null
                || request.getParameter("newPassword")==null
                || request.getParameter("confirmPassword")==null)
        {
            pr.setMessage("缺少必要的参数");
            pr.setCode(String.valueOf(returnCode.ERROR.ordinal()));
            return JSON.toJSONString(pr);
        }

        String newPassword= request.getParameter("newPassword");
        String confirmPassword= request.getParameter("confirmPassword");
        if(!newPassword.equalsIgnoreCase(confirmPassword))
        {
            pr.setMessage("两次密码不一致");
            pr.setCode(String.valueOf(returnCode.ERROR.ordinal()));
            return JSON.toJSONString(pr);
        }

        String verifyCode=request.getParameter("verifyCode");
        String tokenStr= request.getHeader("token");
        token tokenModel=tokenService.getLastTokenModel(tokenStr);
        if(tokenModel==null)
        {
            pr.setMessage("验证码未发送");
            pr.setCode(String.valueOf(returnCode.NOT_FOUND.ordinal()));
            return JSON.toJSONString(pr);
        }

        if(!verifyCode.equalsIgnoreCase(tokenModel.getVerifyCode()))
        {
            pr.setMessage("验证码不正确");
            pr.setCode(String.valueOf(returnCode.ERROR.ordinal()));
            return JSON.toJSONString(pr);
        }

        String email=request.getParameter("email");

        master user=userService.getMasterByEmail(email);
        if(user!=null){
            user.setPassword(CryptoUtil.MD5(newPassword));
            if(userService.UpdateMaster(user)) {
                pr.setMessage("新密码设置成功");
                pr.setCode(String.valueOf(returnCode.SUCCESS.ordinal()));
                return JSON.toJSONString(pr);
            }
            else
            {
                pr.setMessage("新密码设置失败");
                pr.setCode(String.valueOf(returnCode.ERROR.ordinal()));
                return JSON.toJSONString(pr);
            }
        }
        else
        {
            pr.setMessage("没有找到该用户");
            pr.setCode(String.valueOf(returnCode.NOT_FOUND.ordinal()));
            return JSON.toJSONString(pr);
        }
    }
}
